package com.example.demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect//当前是一个切面
@Component
public class UserAspect {

    @Before("pointcut()")
    public void doBefore(){
        System.out.println("前置通知被执行");
    }

    @After("pointcut()")
    public void doAfter(){
        System.out.println("后置通知被执行");
    }

    @AfterThrowing("pointcut()")
    public void doAfterThrowing(){
        System.out.println("AfterThrowing被执行");
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint)  {
        StopWatch stopWatch = new StopWatch();
        Object ret = null;
//        System.out.println("环绕通知前置方法");
        try {
            stopWatch.start();
            ret = joinPoint.proceed();
            stopWatch.stop();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
//        System.out.println("环绕通知前置方法");
        System.out.println(joinPoint.getSignature().getName() + "执行花费的时间：" +
                stopWatch.getLastTaskTimeMillis() + "ms");
        return ret;
    }



    //定义一个切点(设置拦截规则)
    @Pointcut("execution(* com.example.demo.controller.UserController.*(..))")
    public void pointcut(){
    }

}
